#!/bin/bash

# SPAM3UK 服务器环境诊断脚本
# 用于检测HTTP/2连接问题的环境因素

REPORT_FILE="server_environment_report.txt"

echo "🔍 SPAM3UK 服务器环境诊断报告" | tee $REPORT_FILE
echo "=======================================" | tee -a $REPORT_FILE
echo "检测时间: $(date)" | tee -a $REPORT_FILE
echo "服务器: $(hostname)" | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

# 1. 基本系统信息
echo "📋 1. 系统基本信息" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE
echo "操作系统: $(uname -a)" | tee -a $REPORT_FILE
echo "发行版本: $(cat /etc/os-release 2>/dev/null | head -3)" | tee -a $REPORT_FILE
echo "内核版本: $(uname -r)" | tee -a $REPORT_FILE
echo "主机名: $(hostname)" | tee -a $REPORT_FILE
echo "当前用户: $(whoami)" | tee -a $REPORT_FILE
echo "系统负载: $(uptime)" | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

# 2. 网络环境检查
echo "🌐 2. 网络环境信息" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE
echo "公网IP: $(curl -s --max-time 10 ifconfig.me 2>/dev/null || echo '无法获取')" | tee -a $REPORT_FILE
echo "内网IP: $(hostname -I 2>/dev/null || ip addr show | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}' | head -1)" | tee -a $REPORT_FILE

echo "DNS配置:" | tee -a $REPORT_FILE
cat /etc/resolv.conf | tee -a $REPORT_FILE 2>/dev/null
echo "" | tee -a $REPORT_FILE

echo "路由信息:" | tee -a $REPORT_FILE
route -n | head -5 | tee -a $REPORT_FILE 2>/dev/null
echo "" | tee -a $REPORT_FILE

# 3. Go环境检查
echo "🐹 3. Go开发环境" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE
go version | tee -a $REPORT_FILE 2>/dev/null || echo "Go未安装或不在PATH中" | tee -a $REPORT_FILE
echo "GOOS: $(go env GOOS 2>/dev/null)" | tee -a $REPORT_FILE
echo "GOARCH: $(go env GOARCH 2>/dev/null)" | tee -a $REPORT_FILE
echo "GOROOT: $(go env GOROOT 2>/dev/null)" | tee -a $REPORT_FILE
echo "GOPATH: $(go env GOPATH 2>/dev/null)" | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

# 4. Ford网站连接测试
echo "🎯 4. Ford网站连接诊断" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE

echo "DNS解析测试:" | tee -a $REPORT_FILE
if command -v dig >/dev/null 2>&1; then
    dig +short www.ford.co.uk | tee -a $REPORT_FILE
else
    nslookup www.ford.co.uk | tee -a $REPORT_FILE 2>/dev/null
fi
echo "" | tee -a $REPORT_FILE

echo "连接延迟测试:" | tee -a $REPORT_FILE
for i in {1..5}; do
    LATENCY=$(curl -o /dev/null -s -w '%{time_total}' --max-time 15 https://www.ford.co.uk/cars 2>/dev/null)
    if [ $? -eq 0 ]; then
        echo "  测试 $i: ${LATENCY}s" | tee -a $REPORT_FILE
    else
        echo "  测试 $i: 连接失败" | tee -a $REPORT_FILE
    fi
done
echo "" | tee -a $REPORT_FILE

echo "HTTP头信息检查:" | tee -a $REPORT_FILE
curl -I -s --max-time 10 https://www.ford.co.uk/cars | head -10 | tee -a $REPORT_FILE 2>/dev/null
echo "" | tee -a $REPORT_FILE

# 5. TLS/SSL环境检查
echo "🔐 5. TLS/SSL环境" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE
echo "OpenSSL版本: $(openssl version 2>/dev/null || echo '未安装')" | tee -a $REPORT_FILE

echo "TLS握手测试:" | tee -a $REPORT_FILE
echo | openssl s_client -connect www.ford.co.uk:443 -servername www.ford.co.uk 2>/dev/null | grep -E "(Protocol|Cipher)" | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

# 6. Chrome/Chromium检查
echo "🌐 6. Chrome/Chromium环境" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE
if command -v google-chrome >/dev/null 2>&1; then
    echo "Chrome: $(google-chrome --version)" | tee -a $REPORT_FILE
elif command -v chromium-browser >/dev/null 2>&1; then
    echo "Chromium: $(chromium-browser --version)" | tee -a $REPORT_FILE
elif command -v chromium >/dev/null 2>&1; then
    echo "Chromium: $(chromium --version)" | tee -a $REPORT_FILE
else
    echo "未找到Chrome/Chromium浏览器" | tee -a $REPORT_FILE
fi

# 检查Chrome依赖
echo "Chrome依赖检查:" | tee -a $REPORT_FILE
for lib in libgconf-2.so.4 libxss1 libappindicator1 libindicator7; do
    if ldconfig -p | grep -q $lib; then
        echo "  ✅ $lib: 已安装" | tee -a $REPORT_FILE
    else
        echo "  ❌ $lib: 缺失" | tee -a $REPORT_FILE
    fi
done
echo "" | tee -a $REPORT_FILE

# 7. Go HTTP客户端测试
echo "🚀 7. Go HTTP客户端行为测试" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE

# 创建测试程序
cat > test_http_behavior.go << 'EOF'
package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
    "time"
)

func main() {
    fmt.Println("=== Go HTTP客户端测试 ===")
    
    // 测试1: 默认HTTP客户端
    fmt.Println("\n1. 默认HTTP客户端测试:")
    client1 := &http.Client{Timeout: 15 * time.Second}
    resp1, err1 := client1.Get("https://www.ford.co.uk/cars")
    if err1 != nil {
        fmt.Printf("  ❌ 错误: %v\n", err1)
    } else {
        fmt.Printf("  ✅ 成功: %s, 协议: %s\n", resp1.Status, resp1.Proto)
        resp1.Body.Close()
    }
    
    // 测试2: 禁用HTTP/2
    fmt.Println("\n2. 禁用HTTP/2测试:")
    tr2 := &http.Transport{
        ForceAttemptHTTP2: false,
        TLSClientConfig: &tls.Config{},
        IdleConnTimeout: 30 * time.Second,
        DisableKeepAlives: true,
    }
    client2 := &http.Client{Transport: tr2, Timeout: 15 * time.Second}
    resp2, err2 := client2.Get("https://www.ford.co.uk/cars")
    if err2 != nil {
        fmt.Printf("  ❌ 错误: %v\n", err2)
    } else {
        fmt.Printf("  ✅ 成功: %s, 协议: %s\n", resp2.Status, resp2.Proto)
        resp2.Body.Close()
    }
    
    // 测试3: 完全自定义配置
    fmt.Println("\n3. 自定义配置测试:")
    tr3 := &http.Transport{
        ForceAttemptHTTP2: false,
        DisableCompression: false,
        DisableKeepAlives: true,
        IdleConnTimeout: 30 * time.Second,
        TLSHandshakeTimeout: 10 * time.Second,
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: false,
            MinVersion: tls.VersionTLS12,
        },
    }
    client3 := &http.Client{Transport: tr3, Timeout: 20 * time.Second}
    
    req3, _ := http.NewRequest("GET", "https://www.ford.co.uk/cars", nil)
    req3.Proto = "HTTP/1.1"
    req3.ProtoMajor = 1
    req3.ProtoMinor = 1
    req3.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36")
    req3.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    req3.Header.Set("Connection", "close")
    
    resp3, err3 := client3.Do(req3)
    if err3 != nil {
        fmt.Printf("  ❌ 错误: %v\n", err3)
    } else {
        fmt.Printf("  ✅ 成功: %s, 协议: %s\n", resp3.Status, resp3.Proto)
        resp3.Body.Close()
    }
}
EOF

echo "编译并运行Go HTTP测试..." | tee -a $REPORT_FILE
if go run test_http_behavior.go 2>&1 | tee -a $REPORT_FILE; then
    echo "" | tee -a $REPORT_FILE
else
    echo "Go HTTP测试执行失败" | tee -a $REPORT_FILE
fi

# 清理测试文件
rm -f test_http_behavior.go

# 8. 网络限制检查
echo "🛡️ 8. 网络限制和防火墙检查" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE

echo "防火墙状态:" | tee -a $REPORT_FILE
if command -v ufw >/dev/null 2>&1; then
    ufw status | tee -a $REPORT_FILE
elif command -v firewalld >/dev/null 2>&1; then
    firewall-cmd --state | tee -a $REPORT_FILE
elif command -v iptables >/dev/null 2>&1; then
    iptables -L INPUT | head -5 | tee -a $REPORT_FILE
else
    echo "未检测到常见防火墙" | tee -a $REPORT_FILE
fi
echo "" | tee -a $REPORT_FILE

echo "SELinux状态:" | tee -a $REPORT_FILE
if command -v getenforce >/dev/null 2>&1; then
    getenforce | tee -a $REPORT_FILE
else
    echo "SELinux未安装" | tee -a $REPORT_FILE
fi
echo "" | tee -a $REPORT_FILE

# 9. 系统资源检查
echo "💻 9. 系统资源状态" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE
echo "内存使用:" | tee -a $REPORT_FILE
free -h | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

echo "磁盘使用:" | tee -a $REPORT_FILE
df -h | head -5 | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

echo "网络连接数:" | tee -a $REPORT_FILE
ss -tuln | wc -l | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

# 10. 环境变量检查
echo "🔧 10. 相关环境变量" | tee -a $REPORT_FILE
echo "----------------------------------------" | tee -a $REPORT_FILE
echo "HTTP_PROXY: ${HTTP_PROXY:-未设置}" | tee -a $REPORT_FILE
echo "HTTPS_PROXY: ${HTTPS_PROXY:-未设置}" | tee -a $REPORT_FILE
echo "NO_PROXY: ${NO_PROXY:-未设置}" | tee -a $REPORT_FILE
echo "GOPROXY: ${GOPROXY:-未设置}" | tee -a $REPORT_FILE
echo "CGO_ENABLED: ${CGO_ENABLED:-未设置}" | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE

# 完成报告
echo "✨ 诊断完成!" | tee -a $REPORT_FILE
echo "=======================================" | tee -a $REPORT_FILE
echo "报告文件: $REPORT_FILE" | tee -a $REPORT_FILE
echo "生成时间: $(date)" | tee -a $REPORT_FILE
echo "" | tee -a $REPORT_FILE
echo "📋 请将此报告文件发送给开发者进行分析" | tee -a $REPORT_FILE

echo ""
echo "🎯 执行完成! 报告已保存到: $REPORT_FILE"
echo "请使用以下命令查看完整报告:"
echo "cat $REPORT_FILE"
echo ""
echo "或者将报告文件传输到本地进行分析。"
